﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using Brjostagjof_H4.Models;



using System.Collections;

namespace Brjostagjof_H4.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        /*
         * TODO - Implement NotFound view - VB
         *      - ViewNews view - VB
         *      - Implement Try & Catch where it applies - Allir
         */

        MonsterRepository monster = new MonsterRepository();

        public ActionResult Index()
        {
            List<Entry> latestEntries = monster.getXLatestArticles(8);
            latestEntries.AddRange(monster.getXLatestNews(5));

            return View(latestEntries);
        }

        public ActionResult Pharmacist()
        {
            return View( monster.getPharmacist() );
        }


        public ActionResult ViewNews(int? id)
        {
            Entry returnNews = new Entry();

            if (id.HasValue)
            {
                try
                {
                    int nr = int.Parse(id.ToString());
                    returnNews = monster.getNewsFromID(nr);

                    return View(returnNews);
                }
                catch (Exception e)
                {
                    
                    throw e;
                }
            }

            return View("NotFound");
        }

        public ActionResult News()
        {
            List<Entry> newsList = new List<Entry>();

            newsList = monster.getNewsPreview(15);

            return View(newsList);
        }

        public ActionResult Category(int? id)
        {
            List<Entry> articleList = new List<Entry>();

            if ( id.HasValue )
            {
                int nr = int.Parse( id.ToString() );
                string cat = monster.getCategoryName(nr);

                articleList = monster.getArticleList(nr);
                ViewData["CurrCat"] = cat;
            }

            return View(articleList);
        }

        public ActionResult Articles()
        {
            return View(monster.getArticlePreview(8));
        }

        public ActionResult ViewArticle(int? id)
        {
            if ( id.HasValue )
            {
                int nr = int.Parse( id.ToString() );
                Entry model = monster.getEntryById(nr);

                if ( model != null )
                    return View(model);
                else
                    return View("NotFound");
            }

            else
                return View("NotFound");
        }

        [Authorize]
        public ActionResult Profile()
        {       
            MonsterRepository rep = new MonsterRepository();
            String strUser = User.Identity.Name;
            var result = rep.getProfileByUserName(strUser);

            ProfileViewModel profileModel = new ProfileViewModel
            {
                userName = strUser,
                fullName = result.fullName,
                email = result.Email,
                phoneNumber = result.phone_number,
                title = result.title
            };
            return View(profileModel);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Profile(FormCollection formData)
        {
            MonsterRepository repository = new MonsterRepository();
            String strUser = User.Identity.Name;
            ProfileViewModel newData = new ProfileViewModel();
            aspnet_Membership p = repository.getProfileByUserName(strUser);

            if (p != null && ModelState.IsValid)
            {
                UpdateModel(newData);
                p.fullName = newData.fullName;
                p.Email = newData.email;
                p.phone_number = newData.phoneNumber;
                p.title = newData.title;
                repository.updateProfile(p, strUser);
                return RedirectToAction("Profile");
            }
            else
            {
                ModelState.AddModelError("", "Netfang er ekki rétt.");
                return View(newData);
            }
        }
         [HttpGet]
        public ActionResult ContactUsView() 
        {
            return View();
        }

        [Authorize]
        public ActionResult Favorites()
        {
            return View();
        }

        [Authorize]
        public ActionResult Timelines()
        {
            var uName = User.Identity.Name;
            var uID = monster.getUserIDByName(uName); // Fetching the user's id

            var result = monster.getDataByUserID(uID);

            //List<Timeline> timeList = new List<Timeline>();

            //foreach(var r in result)
            //{
            //    timeList.Add(r);
            //}

            //return View(timeList);
            return View(result);
        }

        [Authorize]
        [HttpPost]
        public JsonResult CreateTimelineData(string chartID,string x, string y1, string y2)
        {
            BrjostagjofDBDataContext db = new BrjostagjofDBDataContext();
            var uName = User.Identity.Name;
            var uID = monster.getUserIDByName(uName);
            Timeline t = new Timeline();
            if (ModelState.IsValid)
            {
                if (chartID != "null")
                {
                    t.chartID = int.Parse(chartID);
                }
                else
                {
                    t.chartID = monster.getChartIDSequence();
                }
                t.x = int.Parse(x);
                t.y1 = int.Parse(y1);
                if (!string.IsNullOrEmpty(y2))
                    t.y2 = int.Parse(y2);
                else t.y2 = 0;
                t.created_by = uID;
                t.created_date = DateTime.Now;
                t.userID = uID;
                monster.addTimelineData(t);
            }

            var result = new
                        {
                            x = x,
                            y1 = y1,
                            y2 = y2
                        };
            //var userID = monster.getUserIDByName(uName); // Fetching the user's id
            //var result = monster.getDataByUserID(userID);

            return Json(result,JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetChartData(string chartID)
        {
            Dictionary<int, int?> pointDict = new Dictionary<int, int?>();
            if (chartID.ToLower() != "null")
            {
                int id = int.Parse(chartID);
                BrjostagjofDBDataContext db = new BrjostagjofDBDataContext();

                var result = from c in db.Timelines
                             where c.chartID == id
                             orderby c.x ascending
                             select new
                             {
                                 x = c.x,
                                 y1 = c.y1,
                                 y2 = c.y2
                             };

                
                foreach (var point in result)
                {
                    pointDict.Add(point.x, point.y1);                        
                }
            }
            else
            {
                pointDict.Add(0, 0);
            }
            
            return Json(pointDict.ToArray(),JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetChartData2(string chartID)
        {
            Dictionary<int, int?> pointDict = new Dictionary<int, int?>();
            if (chartID.ToLower() != "null")
            {
                int id = int.Parse(chartID);
                BrjostagjofDBDataContext db = new BrjostagjofDBDataContext();

                var result = from c in db.Timelines
                             where c.chartID == id
                             orderby c.x ascending
                             select new
                             {
                                 x = c.x,
                                 y1 = c.y1,
                                 y2 = c.y2
                             };


                foreach (var point in result)
                {
                    pointDict.Add(point.x, point.y2);
                }
            }
            else
            {
                pointDict.Add(0, 0);
            }

            return Json(pointDict.ToArray(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetTableData(string chartID)
        {
            dynamic result;
            BrjostagjofDBDataContext db = new BrjostagjofDBDataContext();
            if (chartID.ToLower() != "null")
            {
                int id = int.Parse(chartID);
                

                result = from c in db.Timelines
                         where c.chartID == id
                         orderby c.x ascending
                         select new
                         {
                             x = c.x,
                             y1 = c.y1,
                             y2 = c.y2
                         };

            }
            else
            {
                result = //from c in db.Timelines
                          new
                         {
                             x = 0,
                             y1 = 0,
                             y2 = 0
                         };
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        public ActionResult ProfileUpdateFailed()
        {
            return View();
        }
       
        [HttpPost]
        public ActionResult ContactUsView(ContactModel n)
        {
            if(ModelState.IsValid)
            {
                monster.addContactUsData(n);
                return RedirectToAction("ContactUsConfirmation");
            }
            return View(n);
        }

        [Authorize(Roles = "Administrators")]
        public ActionResult ContactUsDelete(int id)
        {
            try
            {
                var contact = monster.deleteContactUsData(id);
                return View(contact);
                //Nota þetta fyrir flottari útfærslu, geri bara basic virkni sem akkúrat núna
                //return Content(Boolean.TrueString);
            }
            catch
            {
                return Content(Boolean.FalseString);
            }
        }
        public ActionResult ContactUsConfirmation() 
        {
            return View();
        }

        [Authorize(Roles = "Administrators")]
        public ActionResult ContactUsShowAll()
        {
            var contact = monster.fetchContactUsDataAll();
            return View(contact);
        }        
        
        [Authorize(Roles = "Administrators")]
        public ActionResult ContactUsShowDetail(int id)
        {
            var contact = monster.fetchContactUsById(id);
            return View(contact);
        }

        [Authorize (Roles="Administrators")]
        public ActionResult ContactUsOld()
        {
            var contact = monster.fetchContactUsDataOld();
            return View(contact);
        }

        public ActionResult LoadCategories()
        {
            BrjostagjofDBDataContext db = new BrjostagjofDBDataContext();

            var result = from c in db.Categories
                         orderby c.category_name ascending
                         select new
                         {
                             categoryID = c.ID,
                             categoryName = c.category_name
                         };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SearchResults()
        {
            return View();
        }

        public ActionResult Donate()
        {
            return View(monster.getDonate());
        }

		public ActionResult NotFound()
		{
            return View("NotFound");
	    }

        ///// <summary>
        ///// Gathers data about the questions and delivers to the view for all users.
        ///// </summary>
        ///// <returns>Asked and answered view.</returns>
        //public ActionResult QuestionsAndAnswers()
        //{
        //    List<Question> questions = new List<Question>();

        //    questions = monster.getXLatestQuestions(20);
        //    if (questions != null)
        //    {
        //        return View(questions);
        //    }
        //    return View();
        //}

        //public ActionResult AddQuestion(Question question)
        //{
        //    if (question != null)
        //    {

        //        return RedirectToAction("AddQuestionConfirmed", "Home");
        //    }
        //    return View();
        //}

        [Authorize(Roles = "Administrators")]
        public ActionResult AdAdd()
        {
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize(Roles = "Administrators")]
        public ActionResult AdAdd(AdsModels a)
        {
            var destinationFolder = Server.MapPath("/Content/Images/");
            foreach (string name in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[name] as HttpPostedFileBase;
                var postedFile = Request.Files[name];
                if (postedFile.ContentLength > 0)
                {
                    var fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    fileName = "current.png"; //Done because there was no time to implement sending the actual filename to 
                    //the partial view sidebar
                    var path = System.IO.Path.Combine(destinationFolder, fileName);
                    postedFile.SaveAs(path);
                    a.adimgurl = "/Content/Images/" + fileName.ToString();
                }

            }
            monster.addAdvertisement(a);
            return View(a);
        }
        //Not in use
        public string displayAds(int id)
        {
            var adsUrl = monster.displayAdevertisement(id);
            return adsUrl;
        }       
        
         
    }
        
    
}